#include "gl_helpers.h"
#include "ndk_helpers.h"

// Based (heavily) on code from "OpenGL ES 2.0 Programming Guide",
// Addison-Wesley 2009
GLuint LoadShader(GLenum type, const char* src) {
  GLuint result = 0;

  result = glCreateShader(type);

  if (result) {
    LOGI("created shader %d",result);
    glShaderSource(result, 1, &src, NULL);
    glCompileShader(result);
  } else {
    LOGI("glCreateShader failed: error %d", glGetError());
  }

  if (result && !CheckShaderStatus(result, GL_COMPILE_STATUS)) {
    glDeleteShader(result);
    result = 0;
  }

  return result;
}

bool CheckShaderStatus(GLuint shader, GLenum statusType) {
  GLint ok;
  glGetShaderiv(shader, statusType, &ok);
  if (ok) {
    LOGI("shader %d is ok", shader);
  } else {
    GLint cbInfo = 0;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &cbInfo);
    if (cbInfo > 1) {
      char* infoLog = new char[cbInfo];
      glGetShaderInfoLog(shader, cbInfo, NULL, infoLog);
      LOGW("Error compiling shader: %s", infoLog);
      delete infoLog;
    }
  }

  return !!ok;
}

void printGLString( const char *name, GLenum s )
{
  const char *v = (const char *) glGetString(s);
  LOGI("GL %s = %s\n", name, v);
}
